﻿using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace System.WindowsCe.Mvp.FormHelpers
{
    public static class KioskExtensions
    {
        private static Form _mainForm;

        private static IntPtr _handle = IntPtr.Zero;
        private static IntPtr Hwnd
        {
            get
            {
                if (_handle == IntPtr.Zero)
                {
                    _handle = _mainForm.Handle;
                }

                return _handle;
            }
        }

        public static void StartKiosk(this FormHelper helper, Form mainForm)
        {
            if (mainForm == null)
            {
                throw new ArgumentNullException("mainForm");
            }

            _mainForm = mainForm;

            Start();
        }

        private static void Start()
        {
            _mainForm.ControlBox = false;
            _mainForm.WindowState = FormWindowState.Normal;
            EnableToolbar(false);

            SetWindowPos(Hwnd, 0, 0, 0, Screen.PrimaryScreen.Bounds.Width,
                                          Screen.PrimaryScreen.Bounds.Height, SWP_SHOWWINDOW);
        }

        public static void StopKiosk(this FormHelper helper)
        {
            EnableToolbar(true);
            _mainForm = null;
        }


        private static void EnableToolbar(bool enabled)
        {
            IntPtr taskHandle = FindWindow("HHTaskBar", null);
            if (taskHandle == IntPtr.Zero)
            {
                return;
            }

            ShowWindow(taskHandle, enabled ? SW_SHOW : SW_HIDE);
            EnableWindow(taskHandle, enabled);
        }


        const int SWP_SHOWWINDOW = 0x0040;

        const int SW_HIDE = 0;
        const int SW_SHOW = 1;

        [DllImport("coredll.dll")]
        private static extern bool SetWindowPos(IntPtr hwnd, int hwnd2, int x, int y, int cx, int cy, int uFlags);

        [DllImport("coredll.dll")]
        private static extern IntPtr FindWindow(
            string lpClassName,
            string lpWindowName);

        [DllImport("coredll.dll")]
        private static extern IntPtr ShowWindow(IntPtr hWnd, int visible);

        [DllImport("coredll.dll")]
        private static extern bool EnableWindow(IntPtr hwnd, bool enabled);

        [Flags]
        public enum FullScreenFlags
        {
            SwHide = 0,
            ShowTaskbar = 0x1,
            HideTaskbar = 0x2,
            ShowSipButton = 0x4,
            HideSipButton = 0x8,
            SwRestore = 9,
            ShowStartIcon = 0x10,
            HideStartIcon = 0x20

        }
    }
}